#!/usr/bin/python
# Copyright 2011 Alex K (wtwf.com)

"""Take a .abc tab file and convert it to the keys to press on my melodeon."""

__author__ = 'wtwf.com (Alex K)'

import sys
import re

notes = {
    'C': (1, 'B'),
    'D': (1, 'S'),
    'E': (2, 'B'),
    'F': (2, 'S'),
    'G': (3, 'B'),
    'A': (3, 'S'),
    'B': (4, 'S'),
    'c': (4, 'B'),
    'd': (5, 'S'),
    'e': (5, 'B'),
    'f': (6, 'S'),
    'g': (6, 'B'),
    'a': (7, 'S'),
    'b': (7, 'B'),
    }

MELODEON_KEYS = 'CDEFGABcdefgab'

keys = { 'C': MELODEON_KEYS,
         'D': MELODEON_KEYS[MELODEON_KEYS.find('D'):],
         'G': MELODEON_KEYS[MELODEON_KEYS.find('G'):]
         }


def Main():
  input = None

  for line in file(sys.argv[1]).readlines():
    if len(line) < 2 or line[0] == '%':
      continue
    if line[1] == ':':
      if line[0] == 'K':
        key = line[2:].strip()[0]
        print 'KEY IS: %s' % key
        key_map = keys[key]
      if line[0] == '|':
        input = line
    else:
      if input is None:
        input = line
      else:
        input += line

  print input

  current_button = None
  output = ''
  lines = []

  # Strip out chords (things between "")
  input = re.sub('"[^"]*"', '', input)

  for x in input:
    if x in notes:
      pos = key_map.find(x)
      if pos == -1:
        (button, direction) = (current_button, 'X')
      else:
        (button, direction) = notes[MELODEON_KEYS[pos]]
      if current_button == button:
        output += ' %s' % direction
      else:
        if output:
          lines.append(output)
        output = '%d %s' % (button, direction)
        current_button = button
  if output:
    lines.append(output)

  # Now print it out in as few lines as possible using multiple columns...
  longest = max([len(x) for x in lines])
  cols = 80 / (longest + 3)

  fmt = (('%' + ('-%ds ' % (79 / (cols)))) * (cols - 1)) + '%s'
  rows = len(lines) / cols
  while rows * cols < len(lines):
    rows += 1

  for x in range(rows):
    row = []
    for col in range(cols):
      pos = x + (col * rows)
      if pos < len(lines):
        row.append(lines[pos])
      else:
        row.append('')
    print fmt % tuple(row)


if __name__ == '__main__':
  Main()
